package controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import dao.DinDao;
import model.Din;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DinController {
	@Autowired
	DinDao orderDao;
	
	@RequestMapping("/insertDin")
	public String insertDin(Din d,Model model) {
		if (!isIdExist(d.getCommodityId())) {
			int a = orderDao.insertDin(d);
			if (a > 0) {
				model.addAttribute("message", "订单添加成功");
				System.out.println("成功了！！！");
				System.out.println(d.getCommodityName());
			}
		} else {
			model.addAttribute("message", "id已存在");
		}
		return "redirect:selectAll";
	}
		
	
	@RequestMapping("/selectAll")
	public String selectAll(Model model) {	   
		List<Din> list = orderDao.SelectAll();			
		model.addAttribute("all",list);
		return  "jsp/Welcome.jsp";
	}
	
	@RequestMapping("deleteDin")
	public void deleteDin(int commodityId, HttpServletResponse response) {
		int rows = orderDao.deleteDin(commodityId);
		try {
			if(rows > 0) {
				response.getWriter().write("SUCCESS!!!");
				System.out.println("删除成功！！已经删除 id为 "+commodityId+" 的商品订单");
			} else {
				response.getWriter().write("FAILED!!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	@RequestMapping("updateDin")
	public String updateDin(Din d) {
		int rows = orderDao.updateDin(d);
		if(rows >0) {
			System.out.println("更新成功！id为 :"+d.getCommodityId()+"的订单已经更新");
		}
		return "redirect:selectAll";
	}

	private boolean isIdExist(int id) {
		int dinCount = orderDao.isIdExist(id);
		if (dinCount > 0) {
			return true;
		}
		return false;
	}
}
